#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace AbstractClass.Runtime.Serialization
{
    /// <summary>
    /// Represents a type to json (de)serialize an object which implements <see cref="IJObject"/>.
    /// </summary>
    /// <typeparam name="T">The type to (de)serialize which implements <see cref="IJObject"/>.</typeparam>
    public static class JObjectSerializer<T> where T : IJObject, new()
    {
        /// <summary>
        /// Deserializes an object of type <typeparamref name="T"/> from a json file.
        /// </summary>
        /// <param name="file">JSON file path.</param>
        /// <returns>Deserialized object of type <typeparamref name="T"/>.</returns>
        public static T ReadFile(string file)
        {
            return ReadFile(file, string.Empty);
        }

        /// <summary>
        /// Deserializes an object of type <typeparamref name="T"/> from an encrypted json file.
        /// </summary>
        /// <param name="file">JSON file path.</param>
        /// <param name="password">Password to decrypt the file.</param>
        /// <returns>Deserialized object of type <typeparamref name="T"/>.</returns>
        public static T ReadFile(string file, string password)
        {
            T jObj;
            using (var stream = new FileStream(file, FileMode.OpenOrCreate))
            {
                var streamReader = new StreamReader(stream);
                string content = streamReader.ReadToEnd();

                if (!string.IsNullOrEmpty(password))
                    content = Security.Decrypt(content, password);
                try
                {
                    using (var ms = new MemoryStream())
                    {
                        var sw = new StreamWriter(ms);
                        sw.Write(content);
                        sw.Flush();
                        ms.Position = 0;

                        var ser = new DataContractJsonSerializer(typeof (T));
                        jObj = (T) ser.ReadObject(ms);

                        jObj.Init();
                    }
                }
                catch (SerializationException ex)
                {
                    Trace.WriteLine(ex);
                    jObj = new T();
                }
            }
            return jObj;
        }

        /// <summary>
        /// Serializes an object of type <typeparamref name="T"/> to a json file.
        /// </summary>
        /// <param name="file">JSON file path.</param>
        /// <param name="jObj">An object of type <typeparamref name="T"/> to serialize.</param>
        /// <returns><c>true</c> if operation is successful; otherwise, <c>false</c>.</returns>
        public static bool WriteFile(string file, T jObj)
        {
            return WriteFile(file, jObj, string.Empty);
        }

        /// <summary>
        /// Serializes an object of type <typeparamref name="T"/> to a json file, optionally encrypts the file.
        /// </summary>
        /// <param name="file">JSON file path.</param>
        /// <param name="jObj">An object of type <typeparamref name="T"/> to serialize.</param>
        /// <param name="password">Password to encrypt the file.</param>
        /// <returns><c>true</c> if operation is successful; otherwise, <c>false</c>.</returns>
        public static bool WriteFile(string file, T jObj, string password)
        {
            bool result = false;
            using (var stream = new FileStream(file, FileMode.Create))
            {
                var stringBuilder = new StringBuilder();
                try
                {
                    jObj.Close();
                    using (var ms = new MemoryStream())
                    {
                        var serializer = new DataContractJsonSerializer(typeof (T));
                        serializer.WriteObject(ms, jObj);
                        ms.Flush();

                        ms.Position = 0;
                        var streamReader = new StreamReader(ms);
                        stringBuilder.Append(streamReader.ReadToEnd());
                        result = true;
                    }
                }
                catch (SerializationException ex)
                {
                    Trace.WriteLine(ex);
                }

                string content = stringBuilder.ToString(0, stringBuilder.Length);

                if (!string.IsNullOrEmpty(password))
                    content = Security.Encrypt(content, password);

                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(content);
                streamWriter.Flush();
            }
            return result;
        }
    }
}